<script setup>
import dayjs from 'dayjs';
import { merge } from 'lodash-es';
import { basicLineYAxis } from '@/components/chart/options/baseOptions.js';
import { useWatch, useRequest } from '@/hooks';
import { usePickerOption } from '@/views/hooks.js';
import { useDownload } from '@/hooks/tool.js';
import { getFeeStatistics, energyConsumptionBydate } from '@/api/index.js';
import CECharts from '@/components/chart/CECharts.vue';
import { TableList } from '@/components/MainComponents.js';
const props = defineProps({
  type: { type: String, default: 'ELECTRICITY' },
  inId: { type: String, default: '' },
  areaId: { type: String, default: null },
  radio: { type: String, default: '' },
  activeName: { type: String, default: '' },
});
const typeList = {
  ELECTRICITY: '电',
  WATER: '水',
  AIR: '燃气',
  WARM: '用热',
};
const unitList = {
  ELECTRICITY: 'kwh',
  WATER: 'm³',
  AIR: 'm³',
  WARM: 'KJ',
};
const themeToggleStyle = {
  // 'theme-dark': {},
  // 'theme-light': {},
  ELECTRICITY: {
    backgroundColor: 'rgba(118,230,18,0.5)',
    color: '#76e612',
    quantity: '用电量',
    cost: '电费',
  },
  WATER: {
    backgroundColor: 'rgba(43,201,242,0.5)',
    color: '#2bc9f2',
    quantity: '用水量',
    cost: '水费',
  },
  AIR: {
    backgroundColor: 'rgba(187,167,85,0.5)',
    color: '#bba755',
    quantity: '用气量',
    cost: '燃气费',
  },
  WARM: {
    backgroundColor: 'rgba(255,151,104,0.5)',
    color: '#ff9768',
    quantity: '用热量',
    cost: '供热费',
  },
};
const today = dayjs().format('YYYY-MM-DD');
const seriesArr = [
  {
    type: 'bar',
    barWidth: 25,
    yAxisIndex: 0,
  },
  {
    type: 'line',
    smooth: true,
    showSymbol: false,
    yAxisIndex: 1,
  },
];
const rangeType = ref({
  d: {
    type: 'daterange',
    fmt: 'yyyy-MM-dd',
    default: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')],
    pickerOptions: usePickerOption('d'),
  },
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    default: [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().subtract(1, 'month').format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: {
    type: 'year',
    fmt: 'yyyy',
    default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')],
  },
});
const dateRangeEC = ref(rangeType.value.m.default);
const yearRangeEC = ref({ sYear: null, eYear: null });
const ECParams = ref({
  dateType: 'm',
  dateStart: dateRangeEC.value[0],
  dateEnd: dateRangeEC.value[1],
});
const tableData = ref(null);
const pageObj = ref({
  pageNum: 1,
  pageSize: 10,
});
const columObj = ref({
  index: true,
  columnData: [
    {
      text: true,
      prop: 'key',
      label: '时段',
    },
    {
      text: true,
      prop: 'value1',
      label: '用电量（KWh）',
    },
    {
      text: true,
      prop: 'value2',
      label: '电费（元）',
    },
  ],
});
const options = ref({
  color: ['#76e612', '#eda422'],
  yAxis: [
    { name: '单位：元' },
    merge({}, basicLineYAxis, {
      name: '单位：kWh',
      nameTextStyle: { align: 'right' },
    }),
  ],
  dataset: {
    dimensions: ['key', { name: 'value2', displayName: '电费' }, { name: 'value1', displayName: '用电量' }],
    source: [],
  },
  series: seriesArr,
});
const [feeData, , runFee] = useRequest(energyConsumptionBydate, {
  // defaultParams: [params.value],
  manual: true,
});
const [res, loading, run] = useRequest(getFeeStatistics, {
  manual: true,
  onSuccess: res => {
    options.value.dataset.source = res?.data ?? [];
    tableData.value = res?.data?.slice(0, 10) ?? [];
  },
});
const searchQuery = (isTop = true) => {
  let obj = {
    inId: props.inId,
    areaId: props.activeName === 'building' ? props.areaId : '',
    energyType: props.type,
    projectType: props.radio,
  };
  if (isTop) runFee(obj);
  run({
    ...ECParams.value,
    ...obj,
  });
};
// 开始时间不能大于结束时间
const disabledDateStartEC = ref({
  disabledDate: time => {
    if (yearRangeEC.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRangeEC.value.eYear) || dayjs(time) < dayjs(yearRangeEC.value.eYear).subtract(2, 'year')
      );
    }
  },
});
const disabledDateEC = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRangeEC.value.sYear) || dayjs(time) > dayjs(yearRangeEC.value.sYear).add(2, 'year');
  },
});
const handleECDaterange = val => {
  ECParams.value.dateStart = val?.[0] ?? null;
  ECParams.value.dateEnd = val?.[1] ?? null;
  searchQuery(false);
};
const handleECYearrange = () => {
  ECParams.value.dateStart = yearRangeEC.value.sYear;
  ECParams.value.dateEnd = yearRangeEC.value.eYear;
  searchQuery(false);
};
const getList = e => {
  pageObj.value.pageNum = e.page;
  pageObj.value.pageSize = e.limit;
  tableData.value = res.value.slice((e.page - 1) * e.limit, e.page * e.limit);
};
const radioChange = val => {
  ECParams.value.dateType = val;
  if (val !== 'y') {
    dateRangeEC.value = rangeType.value[val].default;
    ECParams.value.dateStart = dateRangeEC.value[0];
    ECParams.value.dateEnd = dateRangeEC.value[1];
  } else {
    yearRangeEC.value.sYear = rangeType.value.y.default[0];
    yearRangeEC.value.eYear = rangeType.value.y.default[1];
    ECParams.value.dateStart = yearRangeEC.value.sYear;
    ECParams.value.dateEnd = yearRangeEC.value.eYear;
  }
  searchQuery(false);
};
const handleExport = () => {
  let obj = {
    inId: props.inId,
    areaId: props.activeName === 'building' ? props.areaId : '',
    energyType: props.type,
    projectType: props.radio,
  };
  useDownload('/energyservice/Replenish/egenergyConsumptionListResult', { ...ECParams.value, ...obj }, `费用分析.xlsx`);
};
useWatch(
  () => props.type,
  n => {
    options.value.color[0] = themeToggleStyle[n].color;
    options.value.yAxis[1].name = `单位：${unitList[n]}`;
    options.value.dataset.dimensions[1].displayName = themeToggleStyle[n].cost;
    options.value.dataset.dimensions[2].displayName = themeToggleStyle[n].quantity;
    columObj.value.columnData[1].label = `${themeToggleStyle[n].quantity}（${unitList[n]}）`;
    columObj.value.columnData[2].label = `${themeToggleStyle[n].cost}（元）`;
    searchQuery();
  },
);
useWatch([() => props.inId, () => props.areaId], ([n1, n2]) => {
  if (props.activeName === 'building') {
    if (n1 && n2) searchQuery();
  } else {
    if (n1) searchQuery();
  }
});

useWatch(
  () => props.radio,
  n => {
    searchQuery();
  },
);
useWatch(
  () => props.activeName,
  n => {
    searchQuery();
    // if (n === 'building') {
    //   searchQuery();
    // } else {
    //   let obj = {
    //     inId: props.inId,
    //     // areaId: props.areaId,
    //     energyType: props.type,
    //     projectType: props.radio,
    //   };
    //   runFee(obj);
    //   run({
    //     ...ECParams.value,
    //     ...obj,
    //   });
    // }
    // console.log(n, '22222222222222');
  },
);
</script>
<template>
  <div class="u-h100 u-m20 u-ov">
    <div class="u-df-spb u-mb20 u-fs18">
      <span v-if="activeName === 'building'">建筑区域用{{ typeList[type] }}量费用概览</span>
      <span v-else>总{{ themeToggleStyle[type].quantity }}费用概览</span>
      <div class="u-fs16 u-reg-text u-ta-r">{{ today }}</div>
    </div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="u-base-fg u-br4 fee-statistics u-h-100">
          <div class="u-p20 u-df-spb">
            <span class="u-fs18">年度累计{{ typeList[type] }}费</span>
            <span class="u-red u-fs14">*截止上月月底</span>
          </div>
          <ul :style="themeToggleStyle[type]" class="u-df-st fee-quantity">
            <li class="u-df-spb">
              <span class="u-sec-text">{{ themeToggleStyle[type].cost }}（元）</span>
              <span class="u-yellow">{{ feeData?.value2 ?? '-' }}</span>
            </li>
            <el-divider direction="vertical" style="height: 100%; border-color: rgba(255, 255, 255, 0.1)" />
            <li class="u-df-spb">
              <span class="u-sec-text">{{ themeToggleStyle[type].quantity }}（{{ unitList[type] }}）</span>
              <span class="u-yellow">{{ feeData?.value1 ?? '-' }}</span>
            </li>
          </ul>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="u-base-fg u-br4 fee-statistics u-h-100">
          <div class="u-p20 u-df-spb">
            <span class="u-fs18">上月累计{{ typeList[type] }}费</span>
          </div>
          <ul :style="themeToggleStyle[type]" class="u-df-st fee-quantity">
            <li class="u-df-spb">
              <span class="u-sec-text">{{ themeToggleStyle[type].cost }}（元）</span>
              <span class="u-yellow">{{ feeData?.value4 ?? '-' }}</span>
            </li>
            <el-divider direction="vertical" style="height: 100%; border-color: rgba(255, 255, 255, 0.1)" />
            <li class="u-df-spb">
              <span class="u-sec-text">{{ themeToggleStyle[type].quantity }}（{{ unitList[type] }}）</span>
              <span class="u-yellow">{{ feeData?.value3 ?? '-' }}</span>
            </li>
          </ul>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="u-base-fg u-br4 fee-statistics u-h-100">
          <div class="u-p20 u-df-spb">
            <span class="u-fs18">本月累计{{ typeList[type] }}费</span>
          </div>
          <ul :style="themeToggleStyle[type]" class="u-df-st fee-quantity">
            <li class="u-df-spb">
              <span class="u-sec-text">{{ themeToggleStyle[type].cost }}（元）</span>
              <span class="u-yellow">{{ feeData?.value6 ?? '-' }}</span>
            </li>
            <el-divider direction="vertical" style="height: 100%; border-color: rgba(255, 255, 255, 0.1)" />
            <li class="u-df-spb">
              <span class="u-sec-text">{{ themeToggleStyle[type].quantity }}（{{ unitList[type] }}）</span>
              <span class="u-yellow">{{ feeData?.value5 ?? '-' }}</span>
            </li>
          </ul>
        </div>
      </el-col>
    </el-row>
    <div class="u-p20 u-mt20 u-mb20 u-base-fg u-br4">
      <div class="u-df-spb">
        <span class="u-fs16">{{ themeToggleStyle[type].quantity }}/{{ typeList[type] }}费</span>
        <el-form :model="ECParams" :inline="true" class="u-df-spb qynh-form">
          <el-form-item prop="dateType" class="u-df-ct">
            <el-radio-group v-model="ECParams.dateType" size="mini" class="u-mr20" @input="radioChange">
              <!-- <el-radio-button label="d">日</el-radio-button> -->
              <el-radio-button label="m">月</el-radio-button>
              <el-radio-button label="y">年</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="rangeType[ECParams.dateType].type !== 'year'">
            <el-date-picker
              v-model="dateRangeEC"
              :type="rangeType[ECParams.dateType].type ?? 'daterange'"
              :key="rangeType[ECParams.dateType].type ?? 'daterange'"
              :value-format="rangeType[ECParams.dateType].fmt ?? 'yyyy-MM-dd'"
              :picker-options="rangeType[ECParams.dateType].pickerOptions"
              :clearable="false"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="mini"
              align="left"
              style="width: 240px"
              @change="handleECDaterange"
            />
          </el-form-item>
          <el-form-item v-else>
            <el-date-picker
              v-model="yearRangeEC.sYear"
              :picker-options="disabledDateStartEC"
              :clearable="false"
              type="year"
              value-format="yyyy"
              placeholder="开始年份"
              size="mini"
              style="width: 115px"
              class="u-mr5"
              @change="handleECYearrange"
            />
            <el-date-picker
              v-model="yearRangeEC.eYear"
              :picker-options="disabledDateEC"
              :clearable="false"
              type="year"
              value-format="yyyy"
              placeholder="结束年份"
              size="mini"
              style="width: 115px"
              @change="handleECYearrange"
            />
          </el-form-item>
        </el-form>
      </div>
      <el-divider />
      <CECharts v-loading="loading" :options="options" type="line" class="chart-box" />
    </div>
    <div class="u-p20 u-base-fg u-br4">
      <div class="u-df-spb u-mb20">
        {{ activeName === 'building' ? '建筑区域' : '' }}{{ themeToggleStyle[type].quantity }}费用列表
        <el-button size="small" type="primary" plain @click="handleExport">导出</el-button>
      </div>
      <TableList
        v-loading="loading"
        :total="res?.length ?? 0"
        :height="530"
        :tableData="tableData"
        :pageObj="pageObj"
        :columObj="columObj"
        @getList="getList"
      ></TableList>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@import './common.scss';

.fee-statistics {
  display: flex;
  flex-direction: column;
}

.fee-quantity {
  height: 36px;
  margin-top: auto;
  border-radius: 0 0 4px 4px;

  > li {
    flex: 1;
    margin: 0 20px;
    font-size: 12px;
    color: rgba(255, 255, 255, 0.6);
  }
}

.dateForm :deep(.el-form-item) {
  margin-bottom: 0;
}

.chart-box {
  height: 300px;
}

.u-h-100 {
  height: 100px;
}

.u-ov {
  overflow-x: hidden;
  overflow-y: auto;
}
.qynh-form ::v-deep .el-form-item {
  margin-bottom: 0;
  margin-right: 0 !important;
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .el-form-item__content {
    display: flex;
    justify-content: center;
    align-items: center;
    line-height: 28px;
  }
}
::v-deep .el-radio-button--mini .el-radio-button__inner {
  padding: 6px 8px;
  height: 28px !important;
  margin-right: 3px;
  border-radius: 0;
}
.u-yellow {
  color: #e59215;
  font-weight: bold;
  font-size: 16px;
}
</style>
